﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Diagnostics;
using WMS.FC.Domain.DomainObject.System;
using WMS.FC.Infrastructure.Common;

namespace WMS.FC.Infrastructure.Filter
{
    public class WCSFilter : FilterBase
    {
        public WCSFilter(ILogger<WCSFilter> logger, IOptions<WmsSettings> options) : base(logger, options)
        {
        }

        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var logEventId = SnowflakeIdHelper.Instance.NextId();
            try
            {
                var userIp = context.HttpContext.Connection.RemoteIpAddress?.ToString();
                if (userIp == null)
                {
                    FailAuthority(context, "获取请求IP失败");
                    return;
                }

                logger.LogInformation($"请求开始:{logEventId}\n请求接口:{context.HttpContext.Request.Path}\n请求IP:{userIp}\n请求参数:{JsonConvert.SerializeObject(context.ActionArguments)}");
                if (userIp != "::1" && userIp != "127.0.0.1" && userIp != "localhost" && options.Value.WcsApi.IndexOf(userIp) < 0)
                {
                    FailAuthority(context, $"IP:{userIp},鉴权失败");
                    return;
                }

                if (context.ActionArguments.ContainsKey("dTO"))
                {
                    var dTO = context.ActionArguments["dTO"] as RequestBase;
                    dTO!.UserInfo = new UserInfo()
                    {
                        UserName = "WCS",
                        UserAccount = "WCS",
                        UserIp = userIp,
                        LastRequestTime = DateTime.Now
                    };
                }

                var stopWatch = new Stopwatch();
                stopWatch.Start();
                var actionExecutedContext = await next();
                stopWatch.Stop();
                logger.LogInformation($"请求结束:{logEventId}\n请求接口:{context.HttpContext.Request.Path}\n响应参数:{JsonConvert.SerializeObject(actionExecutedContext.Result)}\n请求时间:{stopWatch.Elapsed}");
            }
            catch (Exception ex)
            {
                logger.LogError($"请求结束:{logEventId}\n请求接口:{context.HttpContext.Request.Path}\n接口异常:{ex.Message}\n调用堆栈:{ex.StackTrace}\n");
                FilterException(context, ex);
            }
        }
    }
}
